//
//  ShareViewController.m
//  ZhongKeXinHeater
//
//  Created by Kendama on 2017/6/3.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "ShareViewController.h"
#import "PublicGetBindUserApi.h"
#import "DeviceUser.h"
#import "PublicShareDeviceApi.h"
#import "PublicDelDeviceBindUserApi.h"


@interface ShareViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
/** <#Description#> **/
@property(nonatomic,strong) UITextField *phoneTF;
@property(nonatomic,strong) UIButton *shareButton;
@property (nonatomic,strong) NSMutableArray *dataSource;
/** <#Description#> **/
@property(nonatomic,copy) NSString *adminUid;

@end

@implementation ShareViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)refreshBaseControlValue {
    
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back"]];
    [self setNavigationTitle:@"账号分享" titleColor:[UIColor blackColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"D0D0D0"];
    [self masLayoutSubviews];
    
    [self getUserName];
}



#pragma mark -- 事件
- (void)didClickShareButton {
    NSString *phone = self.phoneTF.text;
    if (![_phoneTF.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        return;
    }
    
    [self.phoneTF resignFirstResponder];
    
    PublicShareDeviceApi *api = [[PublicShareDeviceApi alloc]initWithDic:@{@"id":CurrentDevice.deviceUUID,@"mobile":phone}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        
        [SVProgressHUD showSuccessWithStatus:@"分享成功"];
        [self getUserName];
        
    } failure:nil];
}

- (void)getUserName{
    
    PublicGetBindUserApi *api = [[PublicGetBindUserApi alloc]initWithDic:@{@"device_id":CurrentDevice.deviceId}];
    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        [self.dataSource removeAllObjects];
        NSArray *array = request.responseJSONObject[@"data"];
        self.adminUid = request.responseJSONObject[@"admin_uid"];
        for ( NSDictionary *dic in array) {
            
            DeviceUser * model = [DeviceUser yy_modelWithDictionary:dic];
            if ([model.uid isEqualToString:self.adminUid]) {
                [self.dataSource insertObject:model atIndex:0];
            } else {
                [self.dataSource addObject:model];
            }
        }
        [self.tableView reloadData];

    } failure:nil];
    
}

#pragma mark -- 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return px1920Height(154);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return px1920Height(473);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:px1080Width(42)];
    label.textColor = [UIColor colorWithHexString:@"#231916"];
    label.text = @"添加成员";
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).with.offset(px1920Height(67));
        make.left.equalTo(view.mas_left).with.offset(px1080Width(53));
        make.right.equalTo(view.mas_right).with.offset(-px1080Width(53));
        make.height.mas_equalTo(px1920Height(60));
    }];
    
    UIView *phoneView = [[UIView alloc] init];
    phoneView.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    phoneView.layer.cornerRadius = 5;
    phoneView.layer.borderWidth = 0.5;
    [phoneView.layer setMasksToBounds:YES];
    [view addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(label.mas_bottom).with.offset(px1920Height(51));
        make.left.mas_equalTo(view.mas_left).with.offset(px1080Width(53));
        make.right.mas_equalTo(view.mas_right).with.offset(-px1080Width(53));
        make.height.mas_equalTo(px1920Height(110));
    }];
    
    [phoneView addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(phoneView).with.offset(px1920Height(24));
        make.bottom.mas_equalTo(phoneView).with.offset(-px1920Height(24));
        make.left.mas_equalTo(phoneView).with.offset(px1920Height(24));
        make.right.mas_equalTo(phoneView).with.offset(-px1920Height(24));
    }];
    
    
    [view addSubview:self.shareButton];
    [self.shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneView.mas_bottom).with.offset(px1920Height(49));
        make.centerX.mas_equalTo(phoneView.mas_centerX);
        make.width.mas_equalTo(px1080Width(500));
        make.height.mas_equalTo(px1920Height(136));
    }];
    
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceUser *user = self.dataSource[indexPath.row];
    __weak typeof(self) weakSelf = self;

    ShareTableViewCell *cell = [ShareTableViewCell cellWithTableView:tableView];
    cell.deleteBlock = ^{
        [[AlertViewManager shareManager]initWithMessage:@"是否确认删除该成员？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
            if (buttonIndex == 1) {
                PublicDelDeviceBindUserApi *api = [[PublicDelDeviceBindUserApi alloc]initWithDic:@{@"device_id":CurrentDevice.deviceId,@"del_uid":user.uid}];
                [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                    [SVProgressHUD showSuccessWithStatus:request.responseJSONObject[@"errmsg"]];
                    
                    [weakSelf.dataSource removeObject:user];
                    
                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                    
                    [weakSelf.tableView reloadData];
                } failure:nil];
            }
        }];

   
    };
    cell.adminUid = self.adminUid;
    cell.deviceUser = user;
    
    // 分割线对齐左边
    cell.separatorInset = UIEdgeInsetsZero;
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


#pragma mark -- 懒加载
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        
    }
    return _dataSource;
}

- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        [superView addSubview:_tableView];
    }
    return _tableView;
}

- (UITextField *)phoneTF
{
    if(!_phoneTF)
    {
        _phoneTF = [[UITextField alloc]init];
        _phoneTF.placeholder = @"请输入分享的手机号";
        _phoneTF.font = [UIFont systemFontOfSize:px1080Width(42)];
    }
    return _phoneTF;
}

- (UIButton *)shareButton
{
    if(!_shareButton)
    {
        _shareButton = [[UIButton alloc]init];
        [_shareButton setTitle:@"分享" forState:UIControlStateNormal];
        [_shareButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_shareButton addTarget:self action:@selector(didClickShareButton) forControlEvents:UIControlEventTouchUpInside];
        _shareButton.layer.cornerRadius = 20;
        _shareButton.backgroundColor = [UIColor colorWithHexString:@"#D0D0D0"];
    }
    return _shareButton;
}


#pragma mark -- 初始化
- (void)masLayoutSubviews{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView).with.offset(64);
        make.width.equalTo(superView);
        make.bottom.equalTo(superView);
    }];
}

@end
